package org.budo.support.dao.page;

import java.io.Serializable;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

/**
 * 作为分页查询时的参数
 * 
 * @author li
 * @version 1 (2016年6月27日 下午8:12:41)
 * @since Java7
 * @see org.budo.support.dao.page.PageModel
 */
@ToString
@Getter
@Setter
@Accessors(chain = true)
public class Page implements Serializable {
    private static final long serialVersionUID = -6026614354807515441L;

    public static final int PAGE_SIZE_DEFAULT = 10;

    private static final int PAGE_NUMBER_DEFAULT = 1;

    private Integer pageNumber = null;

    private Integer pageSize = null;

    /**
     * 是否要count
     */
    private Boolean count = null;

    private Integer recordCount = 0;

    private String orderBy;

    private Integer offset;

    public static final Page max() {
        return new Page(1, Integer.MAX_VALUE - 1);
    }

    public Page() {
    }

    public Page(Integer pageNumber, Integer pageSize) {
        this.setPageNumber(pageNumber);
        this.setPageSize(pageSize);
    }

    public Page setOffset(Integer offset) {
        this.offset = offset;
        return this;
    }

    /**
     * 起始位置 LIMIT A, B 的 A
     */
    public Integer getOffset() {
        if (null != this.offset) {
            return this.offset;
        }

        int _pageSize = null == this.pageSize ? PAGE_SIZE_DEFAULT : this.pageSize;
        int _pageNumber = null == this.pageNumber ? PAGE_NUMBER_DEFAULT : this.pageNumber;
        return (_pageNumber - 1) * _pageSize;
    }

    public Integer getPageCount() {
        Integer pageSize = null == this.getPageSize() ? PAGE_SIZE_DEFAULT : this.getPageSize();

        Integer remainder = this.getRecordCount() % pageSize;
        Integer quotient = this.getRecordCount() / pageSize;

        return remainder < 1 ? quotient : quotient + 1;
    }

    public Page orderBy(String orderBy) {
        return this.setOrderBy(orderBy);
    }

    public Page setRecordCount(Number recordCount) {
        this.recordCount = recordCount.intValue();
        return this;
    }
}
